package com.zhiyou.dao;

import com.zhiyou.model.Auth;
import com.zhiyou.model.User;
import com.zhiyou.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    public static User getUserByUnameAndUpassword(String uname, String upassword) {
        User user = null;
        Connection conn = DBUtil.getConn();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select * from user where uname = ? and upassword = ?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1,uname);
            ps.setString(2,upassword);
            System.out.println(ps.toString());
            rs=ps.executeQuery();
            if (rs.next()){
                user=new User();
                user.setUid(rs.getInt("uid"));
                user.setUname(rs.getString("uname"));
                user.setUrealname(rs.getString("upassword"));
                user.setUroid(rs.getInt("uroid"));
                user.setUaddTime(rs.getDate("uaddTime"));
                user.setUstatus(rs.getInt("ustatus"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeAll(conn,ps,rs);
        }
        return user;
    }

    public List<Auth> findAuth(User user) {
        ArrayList<Auth> auths=new ArrayList<>();
        Connection conn = DBUtil.getConn();
        PreparedStatement ps = null;
        ResultSet rs = null;
        String sql = "select distinct(a.aid) from role r,user u,auth a,user_role ur,role_auth ra where r.roid=ur.roid and r.roid=ra.roid and ra.aid=a.aid and ur.uid=?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1,user.getUid());
            System.out.println(ps.toString());
            rs=ps.executeQuery();
            while (rs.next()){
                Auth auth = new Auth();
                auth.setAid(rs.getInt("aid"));
                auths.add(auth);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeAll(conn,ps,rs);
        }
        return auths;
    }
}
